package no.ntnu.fp.gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import java.awt.Font;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import com.toedter.calendar.JDayChooser;
import com.toedter.components.JLocaleChooser;
import com.toedter.components.JSpinField;
import com.toedter.calendar.JCalendar;

import javax.swing.DefaultListModel;
import javax.swing.ListModel;
import javax.swing.UIManager;
import javax.swing.JSplitPane;
import javax.swing.SwingConstants;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.ListSelectionModel;

import no.ntnu.fp.net.DBConnection;
import no.ntnu.fp.swingutil.TimeFormatterRegex;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import com.michaelbaranov.microba.calendar.DatePicker;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.beans.PropertyVetoException;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import com.michaelbaranov.microba.calendar.CalendarPane;
import javax.swing.JCheckBox;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComboBox;

import run.Main;

import com.michaelbaranov.microba.common.CommitListener;
import com.michaelbaranov.microba.common.CommitEvent;
import javax.swing.JList;
import javax.swing.AbstractListModel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class ManageAppointment extends JFrame {

	private JPanel contentPane;
	private JTable tableWrapper;
	private DefaultTableModel tableModel; //Main table
	private static JButton btnEdit,btnAdd,btnDelete,btnCancel,btnSave;//Buttons
	private JTextField tStart,tFinish,tDescription; 
	private boolean isMeeting = false;
	private DatePicker datePicker; //Date Picker
	private CalendarPane calendarPane;
	private Calendar calendar = Calendar.getInstance();
	private Date currentDate = calendar.getTime();
	private static DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
	private JLabel lblStatus,lblStatus2; //Status-labels
	private javax.swing.Timer updateTimer; //Timer for timer-functions
	private ButtonSelection buttonSelection = ButtonSelection.NONE;
	private int currentAppointmentId = 0, participantListId = 0;
	private ArrayList<Integer> appointmentIdArray = new ArrayList<Integer>();
	private final Action action = new SwingAction();
	private ArrayList<String> compareList;
	private JCheckBox meetingCheckBox;
	private JComboBox meetingRoomCBox;
	private JLabel lblMeetingRoom;
	private JComboBox participantComboBox;
	private JLabel lblAddParticipant;
	private JList participantList;
	private JScrollPane participantScrollPane;
	private ArrayList<String> participantArray;
	private HashMap<Integer, String> meetingRoomMap;
	private HashMap<String, Integer> reverseMeetingRoomMap;
	private TimeFormatterRegex timeValidator = new TimeFormatterRegex();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Main.dbConn = new DBConnection();
					ManageAppointment frame = new ManageAppointment();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 * @throws PropertyVetoException 
	 */
	public ManageAppointment() throws PropertyVetoException {

		/* 
		 * Timerfunksjon som oppdaterer tabell hvert n'te sekund.
		 * 
		 * */
		long delay = 15 * 1000;
		updateTimer = new javax.swing.Timer(
				(int)delay, new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						updateTable(); //Oppdaterer tabell

					}
				});


		/*
		 * Masse GUI/Swing code
		 * 
		 * */
		participantArray = new ArrayList<String>();
		participantArray.add(Main.user.getName());
		setBackground(Color.WHITE);
		setResizable(false);
		setTitle("Manage Appointments");
		setBounds(100, 100, 1005, 541);
		contentPane = new JPanel();
		contentPane.setBackground(Color.WHITE);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(null);
		setContentPane(contentPane);
		setLocationRelativeTo(null);

		JPanel panel_main = new JPanel();
		panel_main.setBackground(Color.WHITE);
		panel_main.setBounds(255, 5, 542, 496);
		contentPane.add(panel_main);
		panel_main.setLayout(new GridLayout(0, 1, 0, 0));

		JScrollPane scrollPane_1 = new JScrollPane();
		panel_main.add(scrollPane_1);

		tableWrapper = new JTable();
		tableWrapper.setBackground(Color.WHITE);
		tableWrapper.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent arg0) {
				if (tableWrapper.getSelectedRow() >= 0){
					if (!btnEdit.isEnabled() && tableWrapper.isEnabled()) {
						updateTimer.stop();
						updateTimer.start();
						enableButtons();
					}	
				}
				else {
					disableButtons();
				}

			}
		});
		tableWrapper.setFillsViewportHeight(true);
		tableWrapper.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableWrapper.setShowVerticalLines(false);

		scrollPane_1.setViewportView(tableWrapper);
		tableModel = new DefaultTableModel(new Object[][]{},
				new String[] {
				"Start", "Finish", "Description", "Date","Meeting"})
		{	
			boolean[] columnEditables = new boolean[] {
					false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		};
		tableWrapper.setModel(tableModel);
		tableWrapper.getColumnModel().getColumn(0).setPreferredWidth(72);
		tableWrapper.getColumnModel().getColumn(1).setPreferredWidth(76);
		tableWrapper.getColumnModel().getColumn(2).setPreferredWidth(274);
		tableWrapper.getColumnModel().getColumn(3).setPreferredWidth(94);
		tableWrapper.getColumnModel().getColumn(4).setPreferredWidth(54);

		Component horizontalStrut_1 = Box.createHorizontalStrut(20);
		scrollPane_1.setColumnHeaderView(horizontalStrut_1);

		JPanel panel_leftButtons = new JPanel();
		panel_leftButtons.setBackground(UIManager.getColor("Button.background"));
		panel_leftButtons.setBounds(5, 5, 249, 496);
		panel_leftButtons.setBorder(null);
		contentPane.add(panel_leftButtons);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(23, 5, 220, 491);
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);

		Box verticalBox = Box.createVerticalBox();
		verticalBox.setBackground(UIManager.getColor("Button.background"));
		verticalBox.setBorder(null);
		scrollPane.setViewportView(verticalBox);

		btnAdd = new JButton("Add");
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				enableRightFields();
				updateTimer.stop();
				tableWrapper.setEnabled(false);
				calendarPane.setEnabled(false);
				buttonSelection = ButtonSelection.ADD;
				participantList.setModel(new AbstractListModel() {
					String[] values = participantArray.toArray(new String[participantArray.size()]);
					public int getSize() {
						return values.length;
					}
					public Object getElementAt(int index) {
						return values[index];
					}
					});	
				} 
				
			}
		);

		calendarPane = new CalendarPane();
		calendarPane.setShowNoneButton(false);
		calendarPane.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateTable();
				updateTimer.stop();
				updateTimer.start();
			}
		});
		calendarPane.setDate(currentDate);
		verticalBox.add(calendarPane);
		btnAdd.setAlignmentX(Component.CENTER_ALIGNMENT);
		btnAdd.setHorizontalAlignment(SwingConstants.LEFT);
		btnAdd.setFont(new Font("Tahoma", Font.PLAIN, 20));
		verticalBox.add(btnAdd);
		Component rigidArea = Box.createRigidArea(new Dimension(5, 5));
		verticalBox.add(rigidArea);
		btnEdit = new JButton("Edit");
		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateTimer.stop();
				tableWrapper.setEnabled(false);
				calendarPane.setEnabled(false);
				disableButtons();
				btnAdd.setEnabled(false);
				enableRightFields();
				buttonSelection = ButtonSelection.EDIT;
				tStart.setText(tableWrapper.getValueAt(tableWrapper.getSelectedRow(), 0).toString()); //Start time
				tFinish.setText(tableWrapper.getValueAt(tableWrapper.getSelectedRow(), 1).toString());//Finish time
				tDescription.setText(tableWrapper.getValueAt(tableWrapper.getSelectedRow(), 2).toString());//Description
				setDateFromTable(tableWrapper.getSelectedRow(),3);//Date
				currentAppointmentId = appointmentIdArray.get(tableWrapper.getSelectedRow());//AppointmentId
				isMeeting = Boolean.parseBoolean(tableWrapper.getValueAt( //Meeting (true/false)
						tableWrapper.getSelectedRow(), 4).toString());
				meetingCheckBox.setEnabled(false); //Not allowed to change meeting to appointment (and opposite)!
				if(isMeeting){
					meetingCheckBox.setSelected(true);
					setMeetingCheckBox();
					getAttendingParticipants(currentAppointmentId);
					getMeetingRooms();
					
				}

			}
		});
		btnEdit.setEnabled(false);
		btnEdit.setAlignmentX(Component.CENTER_ALIGNMENT);
		btnEdit.setFont(new Font("Tahoma", Font.PLAIN, 20));
		verticalBox.add(btnEdit);

		Component rigidArea_1 = Box.createRigidArea(new Dimension(5, 5));
		verticalBox.add(rigidArea_1);
		btnDelete = new JButton("Delete");
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				currentAppointmentId= appointmentIdArray.get(tableWrapper.getSelectedRow());//AppointmentId
				deleteData(currentAppointmentId); //Run Query
				updateTable();
				disableButtons();
				cancelMeeting();
			}
		});
		panel_leftButtons.setLayout(null);
		btnDelete.setEnabled(false);
		btnDelete.setAlignmentX(Component.CENTER_ALIGNMENT);
		btnDelete.setFont(new Font("Tahoma", Font.PLAIN, 20));
		verticalBox.add(btnDelete);

		Component horizontalStrut = Box.createHorizontalStrut(200);
		verticalBox.add(horizontalStrut);

		Component verticalStrut_4 = Box.createVerticalStrut(200);
		verticalBox.add(verticalStrut_4);
		panel_leftButtons.add(scrollPane);

		JPanel panel = new JPanel();
		panel.setBackground(Color.WHITE);
		panel.setBounds(795, 5, 204, 496);
		contentPane.add(panel);
		panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		Box verticalBox_1 = Box.createVerticalBox();
		panel.add(verticalBox_1);
		
		meetingCheckBox = new JCheckBox("Meeting");
		verticalBox_1.add(meetingCheckBox);
		meetingCheckBox.setBackground(Color.WHITE);
		meetingCheckBox.setEnabled(false);

		Component rigidArea_2 = Box.createRigidArea(new Dimension(160, 25));
		verticalBox_1.add(rigidArea_2);

		JLabel lblDescription = new JLabel("Description");
		lblDescription.setHorizontalAlignment(SwingConstants.CENTER);
		lblDescription.setFont(new Font("Tahoma", Font.BOLD, 12));
		verticalBox_1.add(lblDescription);

		Component verticalStrut = Box.createVerticalStrut(5);
		verticalBox_1.add(verticalStrut);

		tDescription = new JTextField();
		tDescription.setEnabled(false);
		verticalBox_1.add(tDescription);
		tDescription.setColumns(10);

		Component verticalStrut_2 = Box.createVerticalStrut(5);
		verticalBox_1.add(verticalStrut_2);

		JLabel lblStartTime = new JLabel("Start time");
		verticalBox_1.add(lblStartTime);
		lblStartTime.setFont(new Font("Tahoma", Font.BOLD, 12));

		tStart = new JTextField();
		tStart.setEnabled(false);
		verticalBox_1.add(tStart);
		tStart.setColumns(10);

		Component verticalStrut_3 = Box.createVerticalStrut(5);
		verticalBox_1.add(verticalStrut_3);

		JLabel lblFinishTime = new JLabel("Finish time");
		lblFinishTime.setFont(new Font("Tahoma", Font.BOLD, 12));
		verticalBox_1.add(lblFinishTime);

		tFinish = new JTextField();
		tFinish.setEnabled(false);
		tFinish.setColumns(10);
		verticalBox_1.add(tFinish);

		Component verticalStrut_5 = Box.createVerticalStrut(5);
		verticalBox_1.add(verticalStrut_5);

		JLabel lblDate = new JLabel("Date");
		lblDate.setFont(new Font("Tahoma", Font.BOLD, 12));
		verticalBox_1.add(lblDate);


		datePicker = new DatePicker();
		datePicker.setFieldEditable(false);
		datePicker.setEnabled(false);
		verticalBox_1.add(datePicker);

		lblStatus = new JLabel("");
		lblStatus.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblStatus.setForeground(Color.RED);
		verticalBox_1.add(lblStatus);

		lblStatus2 = new JLabel("");
		verticalBox_1.add(lblStatus2);
		
		lblMeetingRoom = new JLabel("Meeting Room");
		lblMeetingRoom.setVisible(false);
		
		Component verticalStrut_1 = Box.createVerticalStrut(5);
		verticalBox_1.add(verticalStrut_1);
		lblMeetingRoom.setFont(new Font("Tahoma", Font.BOLD, 12));
		verticalBox_1.add(lblMeetingRoom);
		
		meetingRoomCBox = new JComboBox();	
		meetingRoomCBox.setEditable(true);
		meetingRoomCBox.setVisible(false);
		meetingRoomCBox.getEditor().getEditorComponent().setFocusable(false);
		verticalBox_1.add(meetingRoomCBox);
		
		Component verticalStrut_7 = Box.createVerticalStrut(5);
		verticalBox_1.add(verticalStrut_7);
		
		lblAddParticipant = new JLabel("Add Participant");
		lblAddParticipant.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblAddParticipant.setVisible(false);
		verticalBox_1.add(lblAddParticipant);
		
		participantComboBox = new JComboBox();
		participantComboBox.setEditable(true);
		participantComboBox.setVisible(false);
		participantComboBox.getEditor().getEditorComponent().setFocusable(false);
		participantComboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {	
				if(notInList((String)participantComboBox.getSelectedItem())){
					participantArray.add((String)participantComboBox.getSelectedItem());
					getMeetingRooms();
					}
					participantList.setModel(new AbstractListModel() {
						String[] values = participantArray.toArray(new String[participantArray.size()]);
						public int getSize() {
							return values.length;
						}
						public Object getElementAt(int index) {
							return values[index];
						}
					});	
			}
		});
		
		verticalBox_1.add(participantComboBox);
		
		Component verticalStrut_6 = Box.createVerticalStrut(5);
		verticalBox_1.add(verticalStrut_6);
		
		participantScrollPane = new JScrollPane();
		participantScrollPane.setVisible(false);
		participantScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		verticalBox_1.add(participantScrollPane);
		
		participantList = new JList();
		participantList.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent keyPress) {
				int key = keyPress.getKeyCode();
			     if (key == KeyEvent.VK_DELETE) {   	 
			    	 removeParticipant();
			        }
				}
		});
		participantList.setVisibleRowCount(5);
		participantScrollPane.setViewportView(participantList);
		participantList.setFont(new Font("Tahoma", Font.BOLD, 13));
		participantList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		participantList.setModel(new AbstractListModel() {
			String[] values = new String[] {"Legg til deltakere"};
			public int getSize() {
				return values.length;
			}
			public Object getElementAt(int index) {
				return values[index];
			}
		});
		
		JLabel lblParticipantsHeader = new JLabel("Participants");
		lblParticipantsHeader.setFont(new Font("Tahoma", Font.BOLD, 13));
		lblParticipantsHeader.setBackground(Color.WHITE);
		participantScrollPane.setColumnHeaderView(lblParticipantsHeader);
			
		
		meetingCheckBox.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				setMeetingCheckBox();
			}
		});	
		
		btnSave = new JButton("Save");
		btnSave.setEnabled(false);
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			
				if(isTimeValid() && isDescriptionValid()) {
				
					// Variable to handle which button was chosen to alter data in right column
					switch(buttonSelection){ 
					
					case EDIT:
						if (!isMeeting){
							editData(tDescription.getText(),tStart.getText(), tFinish.getText(), datePicker.getDate());
						}
						else {
							editData(tDescription.getText(),tStart.getText(), tFinish.getText(), datePicker.getDate());
							for (String aParticipant : participantArray){ //for each participant, add data
								participantListId = getUserIdFromUsername(aParticipant.toString());
								editMeetingData(Main.user.getEmployeeId(), participantListId, currentAppointmentId);
								if(!compareList.contains(aParticipant) && participantListId != (Main.user.getEmployeeId())){
									addMeetingData(Main.user.getEmployeeId(), participantListId, currentAppointmentId);
									}
								}
							}
					break;	
					case ADD:
						if (!meetingCheckBox.isSelected()){
							addData(tDescription.getText(),tStart.getText(), tFinish.getText(), datePicker.getDate());
						}
						else {
							addData(tDescription.getText(),tStart.getText(), tFinish.getText(), datePicker.getDate());
							currentAppointmentId = getLastAppointmentId(); //gets last appointmentId from database
							for (String aParticipant : participantArray){ //for each participant, add data
								participantListId = getUserIdFromUsername(aParticipant.toString());
								if(participantListId != (Main.user.getEmployeeId())){
									addMeetingData(Main.user.getEmployeeId(), participantListId, currentAppointmentId);
									}
								}					
							}
						break;
					}
					updateTimer.start();
					updateTable();
					disableRightFields();
					calendarPane.setEnabled(true);
					tableWrapper.setEnabled(true);
					buttonSelection = ButtonSelection.NONE;
				}
			}
		});

		panel.add(btnSave);
		
		/*
		 * Listener for Cancel-knapp
		 * */
		btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				disableRightFields();
				calendarPane.setEnabled(true);
				tableWrapper.setEnabled(true);
				updateTimer.start();
			}
		});
		btnCancel.setEnabled(false);
		panel.add(btnCancel);
		getParticipants();
		getMeetingRooms();
		updateTable();
		updateTimer.start();
	}
	
	/**
	 * Gets the selected date from calendarPane, 
	 * then generates and runs query that populates table with data
	 */
	private void getAppointment(){
		
		try {
			appointmentIdArray.clear();
			long lowUnixTime = generateLowUnixStamp(generateReadableUnixTime(calendarPane.getDate()));
			long highUnixTime = generateHighUnixStamp(generateReadableUnixTime(calendarPane.getDate()));
			ResultSet appointmentRes = Main.dbConn.selectFromDatabase(
					"SELECT appointment.* FROM appointment,employee WHERE calendarId ="+
					"employee.employeeId AND calendarID ="+ Main.user.getEmployeeId() +" AND date BETWEEN "
					+lowUnixTime+" AND "+ highUnixTime + " ORDER BY appointment.starttime ASC");
			while(appointmentRes.next()) {
				appointmentIdArray.add(appointmentRes.getInt("appointmentId"));
				tableModel.addRow(new Object[] {
						appointmentRes.getString("starttime"),
						appointmentRes.getString("finishtime"),
						appointmentRes.getString("description"),
						dateFormatter.format(new Date(appointmentRes.getLong("date")*1000)),
						isAppointmentMeeting(appointmentRes.getInt("appointmentId"), Main.user.getEmployeeId())
				});
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		tableWrapper.requestFocus();
	}
	/**
	 * Populates the meetingroom Combobox with entries
	 */
	private void getMeetingRooms(){
		try {
			ResultSet appointmentRes = Main.dbConn.selectFromDatabase("SELECT * FROM meetingRoom");
			meetingRoomCBox.removeAllItems();
			meetingRoomMap = new HashMap<Integer, String>();
			reverseMeetingRoomMap = new HashMap<String, Integer>();
			
			while(appointmentRes.next()) {
				meetingRoomMap.put(appointmentRes.getInt("meetingRoomId"), appointmentRes.getString("roomName"));
				reverseMeetingRoomMap.put(appointmentRes.getString("roomName"), appointmentRes.getInt("meetingRoomId"));
				if(appointmentRes.getInt("capacity") >= participantArray.size()){
					String meetingRoomCapacity = appointmentRes.getString("roomName") + "(" +appointmentRes.getInt("capacity") +")";
					meetingRoomCBox.addItem(meetingRoomCapacity);
				}
			}	
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void getParticipants(){
		
		try {
			ResultSet appointmentRes = Main.dbConn.selectFromDatabase("SELECT * FROM employee");
			while(appointmentRes.next()) {
				participantComboBox.addItem(appointmentRes.getString("name"));
				}	
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// Autofocus counts as actionPerformed adds, first selection
		participantArray.remove(1);
		// 
		participantComboBox.setSelectedItem(Main.user.getName());
		
	}
	
	private void getAttendingParticipants(int meetingId){
		compareList = new ArrayList<String>();
		try {
			ResultSet appointmentRes = Main.dbConn.selectFromDatabase(
					"SELECT employee.* FROM employee, meetingRequest WHERE "
					+"employee.employeeId = meetingRequest.recipientId AND "
					+"meetingRequest.meetingId = " + meetingId );
			participantArray.clear();
			while(appointmentRes.next()) {
				participantArray.add(appointmentRes.getString("name"));
				compareList.add(appointmentRes.getString("name"));
				//participantComboBox.addItem(appointmentRes.getString("name"));
				}
			participantArray.add(Main.user.getName());
			participantList.setModel(new AbstractListModel() {
				String[] values = participantArray.toArray(new String[participantArray.size()]);
				public int getSize() {
					return values.length;
				}
				public Object getElementAt(int index) {
					return values[index];
				}
				});	
			} 
		catch (SQLException e) {
			e.printStackTrace();
		}
		// Autofocus counts as actionPerformed adds, first selection
		//participantArray.remove(1);
		// 
		//participantComboBox.setSelectedItem(Main.user.getName());
		
	}
	/**
	 * Retrieves last added appointmentId from user currently logged into system
	 * @return
	 */
	private int getLastAppointmentId(){
		int lastAppointmentId = 0;
		try {
			ResultSet lastAppointmentRes = Main.dbConn.selectFromDatabase(
					"SELECT * FROM appointment WHERE calendarId = "
					+ Main.user.getEmployeeId());
			while(lastAppointmentRes.next()) {
				lastAppointmentId = Integer.parseInt(lastAppointmentRes.getString("appointmentId"));
				}	
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return lastAppointmentId;
		
	}
	
	/**
	 * Retrieves last added appointmentId from user currently logged into system
	 * @return
	 */
	private int getUserIdFromUsername(String name){
		int tempUserId = 0;
		try {
			ResultSet userIdRes = Main.dbConn.selectFromDatabase(
					"SELECT employee.employeeId FROM employee WHERE employee.name = '"
					+ name+"'");
			while(userIdRes.next()) {
				tempUserId = Integer.parseInt(userIdRes.getString("employeeId"));
				}	
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return tempUserId;
		
	}
	
	/**
	 * Checks to see if selected AppointmentId is a Meeting where logged in user == leader
	 * @param tempAppointmentId
	 * @return
	 * @throws SQLException
	 */
	public static boolean isAppointmentMeeting(int tempAppointmentId, int userId) throws SQLException{
		int countRows = 0;
		ResultSet meetingRes = Main.dbConn.selectFromDatabase(
				"SELECT appointment.appointmentId FROM appointment,meetingRequest WHERE meetingRequest.meetingId ="+
				"appointmentId AND appointmentId ='"+ tempAppointmentId +"' AND meetingRequest.employeeId ="+ userId);
		while (meetingRes.next()){
			countRows++;
		}
		if (countRows > 0){
			return true;
		}
		else {
		return false;
		}
	}
	
	/**
	 * Removes all data from table, populates table with new data, updates table.
	 */
	private void updateTable(){
	    tableModel.getDataVector().removeAllElements();
		getAppointment();
		tableWrapper.updateUI();
	}
	
	/**
	 * insert data into the database with the chosen fields 
	 * 
	 * @param description
	 * @param start
	 * @param finish
	 * @param date
	 */
	private void addData(String description,String start,String finish, Date date){
		
		String query = "INSERT INTO `calendarsystem`.`appointment` (" +
		"`appointmentId` ," +
		"`description` ," +
		"`starttime` ," +
		"`finishtime` ," +
		"`date` ," +
		"`calendarId`)" +
		"VALUES (NULL , '"+description+"', '"+start+"', '"+finish+"','"
		+ date.getTime()/1000 + "', " + Main.user.getEmployeeId() +" )";
		
			try {
				Main.dbConn.modifyDatabase(query);
			} catch (SQLException e) {
				e.printStackTrace();
			}		
	}
	/**
	 * Adds meeting data to meetingRequest table in database
	 * @param employeeMeetingId
	 * @param recipientId
	 * @param meetingId
	 */
	private void addMeetingData(int employeeMeetingId, int recipientId, int meetingId){

		String CBoxSelection = (String)meetingRoomCBox.getSelectedItem();
		int roomId = reverseMeetingRoomMap.get(CBoxSelection.substring(0, CBoxSelection.length()-3)); // Removes the capacity from meeting room String
		
		String query = "INSERT INTO `calendarsystem`.`meetingRequest` (" +
		"`meetingRequestId` ," +
		"`employeeId` ," +
		"`recipientId` ," +
		"`status` ," +
		"`meetingRoomId` ," +
		"`meetingId`)" +
		"VALUES (NULL , '"+employeeMeetingId+"', '"+recipientId+"', 'UNKNOWN', '"
		+ roomId +"' ,'"+meetingId+"')";		
			try {
				Main.dbConn.modifyDatabase(query);
			} catch (SQLException e) {
				e.printStackTrace();
			}		
	}

	/**
	 * Update the database entry with the chosen fields
	 * 
	 * @param description
	 * @param start
	 * @param finish
	 * @param date
	 */
	private void editData(String description,String start,String finish, Date date){
		
		String query = "UPDATE `calendarsystem`.`appointment` " +
		"SET `description` =  '"+tDescription.getText()+"'"+
		", `starttime` =  '"+tStart.getText()+"'"+
		", `finishtime` =  '"+tFinish.getText()+"'" + 
		", `date` = '"+ date.getTime()/1000 + 
		"' WHERE `appointment`.appointmentId = '"+ currentAppointmentId+"'"; //tempId = selected rows DatabaseID
		try {
			Main.dbConn.modifyDatabase(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
}
	/**
	 * Edits meeting data in meetingRequest table from database
	 * @param employeeMeetingId
	 * @param recipientId
	 * @param meetingId
	 */
	private void editMeetingData(int employeeMeetingId,int recipientId, int meetingId){
		String CBoxSelection = (String)meetingRoomCBox.getSelectedItem();
		int roomId = reverseMeetingRoomMap.get(CBoxSelection.substring(0, CBoxSelection.length()-3));
			
		String query = "UPDATE `calendarsystem`.`meetingRequest` " +
		"SET `status` = 'UNKNOWN', `meetingRoomId` = '"+ roomId +"' WHERE " +
		"employeeId = '"+employeeMeetingId+"' AND recipientId = '"+ recipientId +
		"' AND meetingId = '"+ meetingId +"'";		
			try {
				Main.dbConn.modifyDatabase(query);
			} catch (SQLException e) {
				e.printStackTrace();
			}		
	}
	/**
	 * Delete the chosen appointment from the list
	 * @param appointmentId id of chosen appointment
	 */
	private void deleteData(int appointmentId){
		
		String query = "DELETE FROM `calendarsystem`.`appointment` " +
				"WHERE `appointmentId` = '"+appointmentId+"'"; // SQL query	
		try {
			Main.dbConn.modifyDatabase(query);
			} 
		catch (SQLException e) {
			e.printStackTrace();
		}
	
}
	
	private void enableButtons(){
		btnDelete.setEnabled(true);
		btnEdit.setEnabled(true);
	}

	private void disableButtons(){
		
		btnDelete.setEnabled(false);
		btnEdit.setEnabled(false);
	}

	private void enableRightFields(){
		tStart.setEnabled(true);
		tFinish.setEnabled(true);
		datePicker.setEnabled(true);
		tDescription.setEnabled(true);
		btnCancel.setEnabled(true);
		btnSave.setEnabled(true);
		meetingCheckBox.setEnabled(true);
		btnAdd.setEnabled(false);
		meetingCheckBox.setEnabled(true);
	
	}

	private void disableRightFields(){
		tStart.setEnabled(false);
		tFinish.setEnabled(false);
		datePicker.setEnabled(false);
		tDescription.setEnabled(false);
		btnCancel.setEnabled(false);
		btnSave.setEnabled(false);
		btnAdd.setEnabled(true);
		meetingCheckBox.setEnabled(false);
		meetingCheckBox.setSelected(false);
		tStart.setText("");
		tFinish.setText("");
		tDescription.setText("");
		lblStatus.setText("");
		lblStatus2.setText("");
		lblMeetingRoom.setVisible(false);
		meetingRoomCBox.setVisible(false);
		participantComboBox.setVisible(false);
		lblAddParticipant.setVisible(false);
		participantScrollPane.setVisible(false);
		buttonSelection = ButtonSelection.NONE;
		// Redesign me
		participantArray = new ArrayList<String>();
		participantArray.add(Main.user.getName());
		participantList.setModel(new AbstractListModel() {
			String[] values = participantArray.toArray(new String[participantArray.size()]);
			public int getSize() {
				return values.length;
			}
			public Object getElementAt(int index) {
				return values[index];
			}
		});
		// Redesign me 
	}
	
	
	/**
	 * 	Creates a Date object from selected table row and parses into datePicker
	 * 	@param tableRow
	 *  @param tableColumn
	 */
	private void setDateFromTable(int tableRow, int tableColumn) {
		try {
			datePicker.setDate(dateFormatter.parse(tableWrapper.getValueAt(tableRow,tableColumn).toString()));
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	/**
	 * Generates a human readable date from a Date object
	 * @param unixDate
	 * @return
	 */
	public static String generateReadableUnixTime(Date unixDate){
		String unixTimeHuman = new java.text.SimpleDateFormat("dd/MM/yyyy").format(unixDate);
		return unixTimeHuman;
	}
	/**
	 * Generates a date in UnixTime where time is set to 00:00:00 
	 * @param humanDate1
	 * @return
	 * @throws ParseException
	 */
	public static long generateLowUnixStamp(String humanDate1) throws ParseException{
		long unixLow = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(humanDate1+" 00:00:00").getTime();
		return unixLow/1000;
	}
	/**
	 * Generates a date in UnixTime where time is set to 23:59:59 
	 * @param humanDate2
	 * @return
	 * @throws ParseException
	 */
	public static long generateHighUnixStamp(String humanDate2) throws ParseException{
		long unixHigh = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(humanDate2+" 23:59:59").getTime();
		return unixHigh/1000;
	}
	
	
	private boolean isTimeValid(){
		try {
			timeValidator.stringToValue(tStart.getText());
		} catch (ParseException e) {	
			tStart.setText("Use format HHMM!");
			return false;
		}
//		
//		if (tStart.getText().length() > 4 || tStart.getText().length() == 0){
//			lblStatus.setText("Wrong parameter");
//			lblStatus2.setText("[Start time]");
//			
//			return false;
//			
//		}
		
		try {
			timeValidator.stringToValue(tFinish.getText());
		} catch (ParseException e) {	
			tFinish.setText("Use format HHMM!");
			return false;
		}
		
//		
		
		
//		else if (tFinish.getText().length() > 4 || tFinish.getText().length() == 0){
//			lblStatus.setText("Wrong parameter");
//			lblStatus2.setText("[Finish time]");
//			return false;
//		}
		
		if(Integer.parseInt(tStart.getText()) > Integer.parseInt(tFinish.getText())){
			tStart.setText("Start before finish!");
			return false;
		}
		return true;
	}
	
	private boolean isDescriptionValid(){
		if (tDescription.getText().length() < 1){
			lblStatus.setText("Wrong parameter");
			lblStatus2.setText("[Description]");
			return false;
		}
		
		return true;
	}
	/**
	 * Sets the visibility if all appropriate fields based on checkBox value
	 */
	private void setMeetingCheckBox(){
		if(meetingCheckBox.isSelected()){
			meetingRoomCBox.setVisible(true);
			lblMeetingRoom.setVisible(true);
			participantComboBox.setVisible(true);
			lblAddParticipant.setVisible(true);
			participantScrollPane.setVisible(true);
		}
		else{
			meetingRoomCBox.setVisible(false);
			lblMeetingRoom.setVisible(false);
			participantComboBox.setVisible(false);
			lblAddParticipant.setVisible(false);
			participantScrollPane.setVisible(false);
		}
	}
	
	private boolean notInList(String comboBoxItem){
		
		for(String arrayItem: participantArray){
			if(arrayItem.equals(comboBoxItem)){
				return false;
			}
		}
		
		return true;
	}
	
	private void removeParticipant(){
		
		switch(buttonSelection){

		case EDIT:

			String query = "DELETE FROM `calendarsystem`.`meetingRequest` " +
			"WHERE `meetingId` = '"+currentAppointmentId+"' AND `recipientId` = " 
			+ getUserIdFromUsername((String)participantList.getSelectedValue()) ; // SQL query
			
			try {
				Main.dbConn.modifyDatabase(query);
				} 
			catch (SQLException e) {
				e.printStackTrace();
			}
			
			participantArray.remove(participantList.getSelectedValue());
			participantList.setModel(new AbstractListModel() {
				String[] values = participantArray.toArray(new String[participantArray.size()]);
				public int getSize() {
					return values.length;
				}
				public Object getElementAt(int index) {
					return values[index];
				}
			});
				
			
			break;

		case ADD:

			participantArray.remove(participantList.getSelectedValue());
			participantList.setModel(new AbstractListModel() {
				String[] values = participantArray.toArray(new String[participantArray.size()]);
				public int getSize() {
					return values.length;
				}
				public Object getElementAt(int index) {
					return values[index];
				}
			});

			break;

		}


	}
	
	private void cancelMeeting(){
		
		String query = "DELETE FROM `calendarsystem`.`meetingRequest` " +
		"WHERE `meetingId` = '"+currentAppointmentId+"'"; // SQL query
		
		try {
			Main.dbConn.modifyDatabase(query);
			} 
		catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	
	public enum ButtonSelection{
		ADD, EDIT, DELETE, NONE;
	}
	
	
	
	private class SwingAction extends AbstractAction {
		public SwingAction() {
			putValue(NAME, "SwingAction");
			putValue(SHORT_DESCRIPTION, "Some short description");
		}
		public void actionPerformed(ActionEvent e) {
		}
	}
}
